layui.use(['form', 'jquery', 'layer'], function() {
	var form = layui.form;
	var $ = layui.jquery;
	var layer = layui.layer;
	let register = document.querySelector('.go-register');
	let registerBox = document.querySelector('.registerBox');
	let loginForm = document.querySelector('.loginForm');
	let password2 = document.querySelector('.password2');
	//自定义验证规则
	form.verify({
		title: function(value) {
			if (value.length < 3) {
				return '标题至少得5个字符';
			}
		},
		pass: [
			/^[\S]{6,12}$/, '密码必须6到12位，且不能出现空格'
		],
		content: function(value) {
			layedit.sync(editIndex);
		},
		//判断两次密码是否相等
		judge: function(value) {
			if (value != password2.value) {
				alert(111)
				return '两次密码不一致'
			}
		}
	});
	//登录
	form.on('submit(login)', function(datas) {
		ajax({
			type: 'post',
			url: 'http://api-breakingnews-web.itheima.net/api/login',
			data: datas.field,
			success: function(res) {
				if(res.status==0){
					//保存用户名到浏览器
					localStorage.setItem('username',datas.field.username);
					//保存token到浏览器
					localStorage.setItem('token',res.token);
					//重定向到用户首页
					window.location.replace("index.html");
				}else{
					layer.msg(res.message); 
				}
				
			},
			error: function(res) {
				console.log(res)
			}
		});
		return false;
	});
	//给去注册绑定点击事件
	register.addEventListener('click', function() {
		//注册区域出现
		registerBox.style.display = 'block';
		//登录区域隐藏
		loginForm.style.display = 'none';
	});
	//注册
	form.on('submit(register)', function(datas) {
		//判断用户名是否重复
		ajax({
			type: 'post',
			url: 'http://api-breakingnews-web.itheima.net/api/reguser',
			data: datas.field,
			success: function(res) {
				if (res.status == 1) {
					layer.msg(res.message); 
				} else {
					//重定向到用户首页
					window.location.replace("login.html");
				}
			}
		});
		return false;
	});
});
